// import { createCellPos } from './translateNumToLetter'
const Excel = require('exceljs')

import FileSaver from 'file-saver'
export var testaaa = function () {
  console.log("...");
}
export var exportExcel = function (luckysheet, value) {
  // 参数为luckysheet.getluckysheetfile()获取的对象
  // 1.创建工作簿，可以为工作簿添加属性
  const workbook = new Excel.Workbook()
  // 2.创建表格，第二个参数可以配置创建什么样的工作表
  if (Object.prototype.toString.call(luckysheet) === '[object Object]') {
    luckysheet = [luckysheet]
  }
  luckysheet.forEach(function (table) {
    console.log('%c [ table ]-17', 'font-size:13px; background:pink; color:#bf2c9f;', table)
    if (table.data.length === 0) return true
    // ws.getCell('B2').fill = fills.
    table.zoomScaleNormal = table.zoomRatio*100
    const worksheet = workbook.addWorksheet(table.name)
    const merge = (table.config && table.config.merge) || {}
    const borderInfo = (table.config && table.config.borderInfo) || {}
    // 3.设置单元格合并,设置单元格边框,设置单元格样式,设置值
    
    setStyleAndValue(table.data, worksheet)
    setMerge(merge, worksheet)
    setBorder(borderInfo, worksheet)
    if(table.visibledatarow.length){
      table.visibledatarow.map((item,index)=>{
        worksheet.getRow(index+1).height = (index>0?item-table.visibledatarow[index-1]:item)/table.zoomRatio*0.77
        console.log('%c [ (index>0?item-table.visibledatarow[index-1]:item)/table.zoomRatio ]-32', 'font-size:13px; background:pink; color:#bf2c9f;', (index>0?item-table.visibledatarow[index-1]:item)/table.zoomRatio)
      })
    }
    if(table.visibledatacolumn.length){
      table.visibledatacolumn.map((item,index)=>{
        worksheet.getColumn(index+1).width = (index>0?item-table.visibledatacolumn[index-1]:item)/table.zoomRatio*0.125
        console.log('%c [ (index>0?item-table.visibledatacolumn[index-1]:item)/table.zoomRatio/10 ]-38', 'font-size:13px; background:pink; color:#bf2c9f;', (index>0?item-table.visibledatacolumn[index-1]:item)/table.zoomRatio/10)
      })
    }
    
    return true
  })

  // return
  // 4.写入 buffer
  const buffer = workbook.xlsx.writeBuffer().then(data => {
    // console.log('data', data)
    const blob = new Blob([data], {
      type: 'application/vnd.ms-excel;charset=utf-8'
    })
    console.log("导出成功！")
    FileSaver.saveAs(blob, `${value}.xlsx`)
  })
  return buffer
}

var setMerge = function (luckyMerge = {}, worksheet) {
  const mergearr = Object.values(luckyMerge)
  mergearr.forEach(function (elem) {
    // elem格式：{r: 0, c: 0, rs: 1, cs: 2}
    // 按开始行，开始列，结束行，结束列合并（相当于 K10:M12）
    worksheet.mergeCells(
      elem.r + 1,
      elem.c + 1,
      elem.r + elem.rs,
      elem.c + elem.cs
    )
  })
}

var setBorder = function (luckyBorderInfo, worksheet) {
  if (!Array.isArray(luckyBorderInfo)) return
  // console.log('luckyBorderInfo', luckyBorderInfo)
  luckyBorderInfo.forEach(function (elem) {
    // 现在只兼容到borderType 为range的情况
    // console.log('ele', elem)
    if (elem.rangeType === 'range') {
      let border = borderConvert(elem.borderType, elem.style, elem.color)
      let rang = elem.range[0]
      // console.log('range', rang)
      let row = rang.row
      let column = rang.column
      for (let i = row[0] + 1; i < row[1] + 2; i++) {
        for (let y = column[0] + 1; y < column[1] + 2; y++) {
          worksheet.getCell(i, y).border = border
        }
      }
    }
    if (elem.rangeType === 'cell') {
      // col_index: 2
      // row_index: 1
      // b: {
      //   color: '#d0d4e3'
      //   style: 1
      // }
      const { col_index, row_index } = elem.value
      const borderData = Object.assign({}, elem.value)
      delete borderData.col_index
      delete borderData.row_index
      let border = addborderToCell(borderData, row_index, col_index)
      // console.log('bordre', border, borderData)
      worksheet.getCell(row_index + 1, col_index + 1).border = border
    }
    // console.log(rang.column_focus + 1, rang.row_focus + 1)
    // worksheet.getCell(rang.row_focus + 1, rang.column_focus + 1).border = border
  })
}
var setStyleAndValue = function (cellArr, worksheet) {
  if (!Array.isArray(cellArr)) return
  cellArr.forEach(function (row, rowid) {
    row.every(function (cell, columnid) {
      if (!cell) return true
      let fill = fillConvert(cell.bg)

      let font = fontConvert(
        cell.ff,
        cell.fc,
        cell.bl,
        cell.it,
        cell.fs,
        cell.cl,
        cell.ul
      )
      let alignment = alignmentConvert(cell.vt, cell.ht, cell.tb, cell.tr)
      let value = ''

      if (cell.f) {
        value = { formula: cell.f, result: cell.v }
      } else if (!cell.v && cell.ct && cell.ct.s) {
        // xls转为xlsx之后，内部存在不同的格式，都会进到富文本里，即值不存在与cell.v，而是存在于cell.ct.s之后
        // value = cell.ct.s[0].v
        cell.ct.s.forEach(arr => {
          value += arr.v
        })
      } else {
        value = cell.v
      }
      //  style 填入到_value中可以实现填充色
      let letter = createCellPos(columnid)
      let target = worksheet.getCell(letter + (rowid + 1))
      // console.log('1233', letter + (rowid + 1))
      for (const key in fill) {
        target.fill = fill
        break
      }
      target.font = font
      target.alignment = alignment
      target.value = value

      return true
    })
  })
}

var fillConvert = function (bg) {
  if (!bg) {
    return {}
  }
  // const bgc = bg.replace('#', '')
  let fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: bg.replace('#', '') }
  }
  return fill
}

var fontConvert = function (
  ff = 0,
  fc = '#000000',
  bl = 0,
  it = 0,
  fs = 10,
  cl = 0,
  ul = 0
) {
  // luckysheet：ff(样式), fc(颜色), bl(粗体), it(斜体), fs(大小), cl(删除线), ul(下划线)
  const luckyToExcel = {
    0: '微软雅黑',
    1: '宋体（Song）',
    2: '黑体（ST Heiti）',
    3: '楷体（ST Kaiti）',
    4: '仿宋（ST FangSong）',
    5: '新宋体（ST Song）',
    6: '华文新魏',
    7: '华文行楷',
    8: '华文隶书',
    9: 'Arial',
    10: 'Times New Roman ',
    11: 'Tahoma ',
    12: 'Verdana',
    num2bl: function (num) {
      return num === 0 ? false : true
    }
  }
  // 出现Bug，导入的时候ff为luckyToExcel的val

  let font = {
    name: typeof ff === 'number' ? luckyToExcel[ff] : ff,
    family: 1,
    size: fs,
    color: { argb: fc.replace('#', '') },
    bold: luckyToExcel.num2bl(bl),
    italic: luckyToExcel.num2bl(it),
    underline: luckyToExcel.num2bl(ul),
    strike: luckyToExcel.num2bl(cl)
  }

  return font
}

var alignmentConvert = function (
  vt = 'default',
  ht = 'default',
  tb = 'default',
  tr = 'default'
) {
  // luckysheet:vt(垂直), ht(水平), tb(换行), tr(旋转)
  const luckyToExcel = {
    vertical: {
      0: 'middle',
      1: 'top',
      2: 'bottom',
      default: 'top'
    },
    horizontal: {
      0: 'center',
      1: 'left',
      2: 'right',
      default: 'left'
    },
    wrapText: {
      0: false,
      1: false,
      2: true,
      default: false
    },
    textRotation: {
      0: 0,
      1: 45,
      2: -45,
      3: 'vertical',
      4: 90,
      5: -90,
      default: 0
    }
  }

  let alignment = {
    vertical: luckyToExcel.vertical[vt],
    horizontal: luckyToExcel.horizontal[ht],
    wrapText: luckyToExcel.wrapText[tb],
    textRotation: luckyToExcel.textRotation[tr]
  }
  return alignment
}

var borderConvert = function (borderType, style = 1, color = '#000') {
  // 对应luckysheet的config中borderinfo的的参数
  if (!borderType) {
    return {}
  }
  const luckyToExcel = {
    type: {
      'border-all': 'all',
      'border-top': 'top',
      'border-right': 'right',
      'border-bottom': 'bottom',
      'border-left': 'left'
    },
    style: {
      0: 'none',
      1: 'thin',
      2: 'hair',
      3: 'dotted',
      4: 'dashDot', // 'Dashed',
      5: 'dashDot',
      6: 'dashDotDot',
      7: 'double',
      8: 'medium',
      9: 'mediumDashed',
      10: 'mediumDashDot',
      11: 'mediumDashDotDot',
      12: 'slantDashDot',
      13: 'thick'
    }
  }
  let template = {
    style: luckyToExcel.style[style],
    color: { argb: color.replace('#', '') }
  }
  let border = {}
  if (luckyToExcel.type[borderType] === 'all') {
    border['top'] = template
    border['right'] = template
    border['bottom'] = template
    border['left'] = template
  } else {
    border[luckyToExcel.type[borderType]] = template
  }
  // console.log('border', border)
  return border
}

function addborderToCell(borders, row_index, col_index) {
  let border = {}
  const luckyExcel = {
    type: {
      l: 'left',
      r: 'right',
      b: 'bottom',
      t: 'top'
    },
    style: {
      0: 'none',
      1: 'thin',
      2: 'hair',
      3: 'dotted',
      4: 'dashDot', // 'Dashed',
      5: 'dashDot',
      6: 'dashDotDot',
      7: 'double',
      8: 'medium',
      9: 'mediumDashed',
      10: 'mediumDashDot',
      11: 'mediumDashDotDot',
      12: 'slantDashDot',
      13: 'thick'
    }
  }
  // console.log('borders', borders)
  for (const bor in borders) {
    // console.log(bor)
    if (borders[bor].color.indexOf('rgb') === -1) {
      border[luckyExcel.type[bor]] = {
        style: luckyExcel.style[borders[bor].style],
        color: { argb: borders[bor].color.replace('#', '') }
      }
    } else {
      border[luckyExcel.type[bor]] = {
        style: luckyExcel.style[borders[bor].style],
        color: { argb: borders[bor].color }
      }
    }
  }

  return border
}

function createCellPos(n) {
  let ordA = 'A'.charCodeAt(0)

  let ordZ = 'Z'.charCodeAt(0)
  let len = ordZ - ordA + 1
  let s = ''
  while (n >= 0) {
    s = String.fromCharCode((n % len) + ordA) + s

    n = Math.floor(n / len) - 1
  }
  return s
}
export const en = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
]
// 列计算A-ZZ
export function columnFilter(num) {
  if (typeof num === 'number') {
    let str = ''
    if (num / 26 >= 1) {
      str = en[Math.floor(num / 26 - 1)]
    }
    return str + en[num % 26]
  }
  return ''
};

// 列反向计算
export function unColumnFilter(c) {
  if (c === c.toUpperCase()) {
    let str = 0
    c.split('').map((item, index) => {
      str = str + en.indexOf(item) + index * en.length
    })
    return str
  }
  return null
};

export const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
}
export const formRowLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
}
// 指标列表表头
export const columns = [
  {
    title: '指标代码',
    dataIndex: 'zbdm',
    ellipsis: true,
    scopedSlots: { customRender: 'zbdm' },
  },
  {
    title: '指标名称',
    dataIndex: 'zbmc',
    ellipsis: true,
    scopedSlots: { customRender: 'zbmc' },
  },
];
// 栏位列表表头
export const headColumns = [
  {
    title: '报表代码',
    dataIndex: 'bbdm',
    ellipsis: true,
    scopedSlots: { customRender: 'bbdm' },
  },
  {
    title: '栏位编码',
    dataIndex: 'lwbm',
    ellipsis: true,
  },
  {
    title: '栏位名称',
    dataIndex: 'lwmc',
    ellipsis: true,
  },
  {
    title: '指标数据类型',
    dataIndex: 'zblx',
    ellipsis: true,
    scopedSlots: { customRender: 'zblx' },
  },
  {
    title: '生效日期',
    dataIndex: 'startrq',
    ellipsis: true,
  },
  {
    title: '失效日期',
    dataIndex: 'endrq',
    ellipsis: true,
  },
];
// 数据集区域列表表头
export const dataSysColumns = [
  {
    title: '区域名称',
    dataIndex: 'xzmc',
    ellipsis: true,
  },
  {
    title: '坐标',
    dataIndex: 'xzqy',
    scopedSlots: { customRender: 'xzqy' },
  },
  {
    title: 'SQL语句',
    dataIndex: 'sqlval',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    ellipsis: true,
    scopedSlots: { customRender: 'action' },
  },
];
// 数据集规则列表表头
export const sjjRuleColumns = [
  {
    title: '区域',
    dataIndex: 'rangeId',
    scopedSlots: { customRender: 'rangeId' },
  },
  {
    title: '范围',
    dataIndex: 'syfw',
    ellipsis: true,
  },
  {
    title: '字段',
    dataIndex: 'yzzd',
    ellipsis: true,
  },
  {
    title: '过滤条件',
    dataIndex: 'gltj',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '130px',
    scopedSlots: { customRender: 'action' },
  },
];
// 指标规则列表表头
export const targetRuleColumns = [
  {
    title: '指标名称',
    dataIndex: 'gltj',
    scopedSlots: { customRender: 'gltj' },
    ellipsis: true,
  },
  {
    title: '验证公式',
    dataIndex: 'yzgs',
    ellipsis: true,
  },
  {
    title: '提示说明',
    dataIndex: 'tssm',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '130px',
    scopedSlots: { customRender: 'action' },
  },
]
// redonly只读
export const optionsRedonly = {
  myFolderUrl: false, //左上角<返回按钮的链接
  allowCopy: false, // 是否允许拷贝
  showtoolbar: false, // 是否显示工具栏
  showinfobar: true, // 是否显示顶部信息栏
  showsheetbar: false, // 是否显示底部sheet页按钮
  showstatisticBar: false, // 是否显示底部计数栏
  sheetBottomConfig: false, // sheet页下方的添加行按钮和回到顶部按钮配置
  allowEdit: false, // 是否允许前台编辑
  enableAddRow: false, // 允许增加行
  enableAddCol: false, // 允许增加列
  userInfo: false, // 右上角的用户信息展示样式
  showRowBar: false, // 是否显示行号区域
  showColumnBar: false, // 是否显示列号区域
  sheetFormulaBar: false, // 是否显示公式栏
  enableAddBackTop: true, //返回头部按钮
  autoFormatw: false, //自动格式化超过4位数的数字为‘亿万格式’
  row: 84, //空表格默认的行数据量
  showstatisticBarConfig: {
    count: false,
    view: false,
    zoom: true,
  },
  showsheetbarConfig: {
    add: false, //新增sheet
    menu: false, //sheet管理菜单
    sheet: false, //sheet页显示
  },
  forceCalculation: true, //强制计算公式
  cellRightClickConfig: {
    copy: false, // 复制
    copyAs: false, // 复制为
    paste: false, // 粘贴
    insertRow: false, // 插入行
    insertColumn: false, // 插入列
    deleteRow: false, // 删除选中行
    deleteColumn: false, // 删除选中列
    deleteCell: false, // 删除单元格
    hideRow: false, // 隐藏选中行和显示选中行
    hideColumn: false, // 隐藏选中列和显示选中列
    rowHeight: false, // 行高
    columnWidth: false, // 列宽
    clear: false, // 清除内容
    matrix: false, // 矩阵操作选区
    sort: false, // 排序选区
    filter: false, // 筛选选区
    chart: false, // 图表生成
    image: false, // 插入图片
    link: false, // 插入链接
    data: false, // 数据验证
    cellFormat: false, // 设置单元格格式
  }, //自定义单元格右键菜单
}
